package com.adjaisd.scarecrow.repo;

import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class TimeSeriesRepository {

    @Autowired
    InfluxDB influxDB;

    @Value("${spring.influx.database}")
    private String database;

    public void add(Object object) {
        Point.Builder pointBuilder = Point.measurementByPOJO(object.getClass());

        Point point = pointBuilder.addFieldsFromPOJO(object)
                .time(LocalDateTime.now().plusHours(8).toInstant(ZoneOffset.of("+8")).toEpochMilli(), TimeUnit.MILLISECONDS)
                .build();
        influxDB.setDatabase(database);
        influxDB.write(point);
        influxDB.close();
    }


    // 查询数据
    public <T> List<T> query(String ql, Class<T> clazz) {
        System.out.println("query = " + ql);
        QueryResult queryResult = influxDB.query(new Query(ql, database));
        influxDB.close();
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return resultMapper.toPOJO(queryResult, clazz);
    }
}
